<template>
  <div class="flex flex-wrap w-screen h-screen pb-safe relative">
    <div
      v-for="(item, index) in sortList"
      id="wrapper"
      :key="item.key"
      class="overflow-y-scroll box-border w-1/2 h-1/2 b-white border-2 border-solid"
      :style="{ backgroundColor: BG_ENUM[index] }"
    >
      <div
        class="font-medium text-14px h-24px flex items-center justify-between px-2 sticky top-0 z-9"
        :style="{
          color: COLOR_ENUM[index],
          backgroundColor: TITLE_BG_ENUM[index]
        }"
      >
        <div class="flex">
          <div>{{ item.key }}</div>
          <div class="ml-1">{{ item.title }}</div>
        </div>
        <wd-icon name="add" @click="toAddItem(item.key, 'add')" />
      </div>
      <template v-for="(sub, idx) in item.items" :key="idx">
        <view
          :style="
            String(index) + '-' + String(idx) === currentIndex ? moveStyle : ''
          "
          class="flex items-center h-40px w-full pl-1 pt-3 box-border"
          @touchstart="handleTouchStart($event)"
          @touchmove="
            handleTouchMove($event, String(index) + '-' + String(idx))
          "
          @touchend="handleTouchEnd($event)"
        >
          <wd-checkbox
            v-model="sub.isDone"
            custom-class="center flex-shrink-0"
            :checked-color="COLOR_ENUM[index]"
          />
          <view
            :class="{ 'line-through': sub.isDone }"
            class="truncate"
            @click="toAddItem(item.key, 'edit', sub.name)"
          >
            {{ sub.name }}
          </view>
        </view>
        <!-- 拖动时占位 -->
        <view
          v-if="String(index) + '-' + String(idx) === currentIndex"
          class="h-40px w-full pl-1 pt-3 box-border flex items-center"
        >
          <wd-checkbox
            v-model="sub.isDone"
            custom-class="center flex-shrink-0"
            :checked-color="COLOR_ENUM[index]"
          >
            <view class="truncate">
              {{ sub.name }}
            </view>
          </wd-checkbox>
        </view>
      </template>
    </div>
  </div>
</template>

<script setup lang="ts">
import { preventScroll, restoreScroll } from '@/utils/common';
import { throttle } from 'wot-design-uni/components/common/util';
import { BG_ENUM, TITLE_BG_ENUM, COLOR_ENUM } from '@/enums';
import type {
  Quadrant,
  EditType,
  FourDomRect,
  FourQuadrant,
  QuadrantItem
} from '@/api/record/type';
import { useRecordStore } from '@/store';

const toAddItem = (key: Quadrant, type: EditType, name = '') => {
  uni.navigateTo({
    url: `/pages/fourQuadrant/addItem/index?key=${key}&type=${type}&name=${name}`
  });
};

const fourDomRect = ref<FourDomRect[]>([]);
const fourQuadrantList = ref<FourQuadrant[]>(useRecordStore().list);
const sortList = computed(() => {
  return fourQuadrantList.value.map((item) => {
    return {
      ...item,
      items: item.items.sort((a, b) => Number(a.isDone) - Number(b.isDone))
    };
  });
});

const currentIndex = ref('');
const moveStyle = ref('');
const startPos = reactive({
  x: 0,
  y: 0
});
const endPos = reactive({
  x: 0,
  y: 0
});

const setMoveStyle = (distanceX: number, distanceY: number) => {
  console.log('打印***distanceX,distanceY', distanceX, distanceY);
  preventScroll();
  if (distanceX !== 0 || distanceY !== 0) {
    moveStyle.value = `
    position: absolute;
    display: block;
    width: 40%;
    transform: translateX(${distanceX}px) translateY(${distanceY}px);
    background-color: #efefef;
    `;
  } else {
    moveStyle.value = '';
  }
  restoreScroll();
};

const isClick = ref(true);
const handleTouchStart = (e: TouchEvent) => {
  console.log('打印***e', e);
  isClick.value = true;
  startPos.x = e.changedTouches[0].pageX;
  startPos.y = e.changedTouches[0].pageY;
};

const handleTouchMove = throttle((e: TouchEvent, index: string) => {
  if (!startPos.x && !endPos.y) return;
  isClick.value = false;
  currentIndex.value = index;

  endPos.x = e.changedTouches[0].clientX;
  endPos.y = e.changedTouches[0].clientY;

  const distanceX = endPos.x - startPos.x;
  const distanceY = endPos.y - startPos.y;
  console.log('打印***move', e);

  setMoveStyle(distanceX, distanceY);
}, 14);

const handleTouchEnd = (e: TouchEvent) => {
  console.log('打印***end', e);
  // 判断是否移动到其他象限，数据处理
  console.log('打印***startPos', startPos);
  console.log('打印***endPos', endPos);
  if (!isClick.value) {
    moveByPos(e, currentIndex.value);
  }
  setMoveStyle(0, 0);
  currentIndex.value = '';
  startPos.x = 0;
  startPos.y = 0;
  endPos.x = 0;
  endPos.y = 0;
};

/** 判断鼠标位置在哪一个象限 */
const moveByPos = (e: TouchEvent, curIndex: string) => {
  const { clientX, clientY } = e.changedTouches[0];
  console.log('打印***clientX, clientY', clientX, clientY, curIndex);
  let inIndex = 0;
  for (let i = 0; i < fourDomRect.value.length; i++) {
    const { xmax, xmin, ymin, ymax } = fourDomRect.value[i];
    if (clientX > xmin && clientX < xmax && clientY > ymin && clientY < ymax) {
      inIndex = i;
    }
  }

  const [index, subIdx] = curIndex.split('-').map(Number);
  console.log('打印***curIndex', index, subIdx);

  if (inIndex === index) return;

  const item = fourQuadrantList.value[index].items.splice(subIdx, 1);
  fourQuadrantList.value[inIndex].items.splice(0, 0, ...item);
};

const getFourRect = () => {
  const instance = getCurrentInstance();
  uni
    .createSelectorQuery()
    .in(instance)
    .selectAll('#wrapper')
    .boundingClientRect((data) => {
      console.log('打印***data', data);
      if (Array.isArray(data)) {
        fourDomRect.value = data.map((item) => ({
          xmin: item.left || 0,
          xmax: (item.left || 0) + (item.width || 0),
          ymin: item.top || 0,
          ymax: (item.top || 0) + (item.height || 0)
        }));
      }
    })
    .exec();
};

onMounted(() => {
  getFourRect();
});
</script>

<style lang="scss" scoped></style>
